
import store from '../store'
import conf from '../config/config'
import code from '../config/code'

import key from '../config/constant'

import { goLogin } from './platform'

const sessionKey = key.sessionKey
const referrerKey = key.referrerKey

export default class Request {
  request({ url, data = {}, method = 'POST' }) {
    return new Promise((resolve, reject) => {

      // 处理全局apis请求
      // 主要处理H5的
      if (conf.baseUrl == 'http://192.168.0.213:9018') {
        url = url.replace('/apis', '')
      }


      uni.request({
        url: `${conf.baseUrl}${url}`,
        data,
        method,
        // sslVerify: false,
        header: {
          'content-type': 'application/json;charset=utf8mb4',
          'X-TOKEN-zheng': store.getters['User/token'] || ''
        },
        success: response => {
          const { data } = response
          if (data.code === code.CODE_SUCCESS) {
            resolve(data)
          } else if (data.code === code.CODE_TOKEN_EXPIRED) {
            // 未登录
            uni.showToast({
              title: '您还没有登录,请登录!',
              icon: 'none',
              duration: 1000
            })
            setTimeout(() => {
              // uni.navigateTo({
              //   url: '/sub_common/user/login'
              // })
              goLogin()
            }, 500)
          } else {
            if (data.code === code.CODE_ERROR) {
              uni.showToast({
                title: data.message,
                icon: 'none',
                duration: 1000
              })
            } else if (data.code === code.CODE_ERROR_CUSTOM) {
              console.log(data)
              uni.showToast({
                title: data.message.split('/\s/')[0],
                icon: 'none',
                duration: 1000
              })
            } else {
              // reject(data.message)
              console.log(data)
            }
          }
        }
      })

    })
  }

  // 测试
  test() {
    return this.request({
      url: '/site/test',
      data: { title: '123', age: 'abc' },
      method: 'POST'
    })
  }

  setSessionKey(data) {
    uni.setStorageSync(sessionKey, data)
  }

  getSessionKey() {
    return uni.getStorageSync(sessionKey)
  }

  setReferrer(id) {
    uni.setStorageSync(referrerKey, id)
  }

  getReferrer() {
    return uni.getStorageSync(referrerKey)
  }
}
